import { formatCurrency, pickBy, pickData } from './base';

export function categoryNameToPathString(str: string) {
  return str
    .toLowerCase()
    .replace(/[^a-zA-Z0-9]/g, '-')
    .replace(/-+/g, '-');
}

export function getCategoryFullPaths(category: Obj, categories: any[]) {
  const paths: any[] = [];
  let cat = category;
  while (cat && cat.parent_id != 1 && cat.category_id != 1) {
    paths.unshift({
      n: categoryNameToPathString(cat.title),
      i: cat.category_id,
    });
    cat = categories.find((c: any) => c.category_id == cat.parent_id);
  }
  return { category, paths };
}
export function getCategoryByPaths(paths: any[], categories: any[]) {
  if (paths?.length && categories?.length) {
    const targetPath = paths.join('/');
    const res = categories?.find((c: any) => c.format_paths == targetPath);
    return res || null;
  } else {
    return null;
  }
}

export function parseSearchParams(searchParams?: Obj) {
  if (searchParams) {
    const params: Obj<any> = {};
    // Search
    if (searchParams.q) {
      // params.keywords = decodeURIComponent(searchParams.q);
      params.keywords = searchParams.q;
    }
    // Page
    if (parseInt(searchParams.p)) {
      params.page_no = parseInt(searchParams.p);
    }
    if (parseInt(searchParams.limit)) {
      params.limit = parseInt(searchParams.limit);
    }
    // Order
    if (searchParams.order) {
      params.sort_by = searchParams.order;
    }
    if (searchParams.dir) {
      params.sort_order = searchParams.dir;
    }
    // Category
    if (parseInt(searchParams.cat)) {
      params.category_id = parseInt(searchParams.cat);
    }
    // Filters
    if (searchParams.au_free_shipping) {
      params.au_free_shipping =
        searchParams.au_free_shipping.toString() == 'false' ? false : true;
    }
    if (searchParams.nz_available) {
      params.nz_available =
        searchParams.nz_available.toString() == 'false' ? false : true;
    }
    if (searchParams.direct_import) {
      params.direct_import =
        searchParams.direct_import.toString() == 'false' ? false : true;
    }
    if (searchParams.on_promotion) {
      params.on_promotion =
        searchParams.on_promotion.toString() == 'false' ? false : true;
    }
    if (searchParams.in_stock) {
      params.in_stock =
        searchParams.in_stock.toString() == 'false' ? false : true;
    }
    if (searchParams.on_my_sku_list) {
      params.on_my_sku_list =
        searchParams.on_my_sku_list.toString() == 'false' ? false : true;
    }
    if (searchParams.discontinued) {
      params.discontinued =
        searchParams.discontinued.toString() == 'false' ? false : true;
    }
    if (searchParams.price) {
      params.price = searchParams.price;
    }
    if (searchParams.recently) {
      const startISODate = new Date(
        new Date().setDate(new Date().getDate() - searchParams.recently)
      ).toISOString();
      params.approve_time = startISODate + '-';
    }
    return params;
  } else {
    return {};
  }
}

export function filtersToSearchParams(filtersList: Obj) {
  const newParams: Obj = {};
  Object.values(filtersList).forEach((item: any) => {
    newParams[item.datakey] = item.value;
  });
  return newParams;
}

export function searchParamsToFilters(searchParams: Obj, categoryList?: any[]) {
  const res: Obj = {};
  Object.keys(searchParams).forEach((paramKey: any) => {
    const ft = {
      datakey: paramKey,
      value: searchParams[paramKey],
      title: paramKey,
    };
    const newft = checkFilterTitle(ft, categoryList);
    if (newft) res[paramKey] = newft;
  });
  return res;
}

const filterKeyTitleMap = [
  { datakey: 'au_free_shipping', value: true, title: 'Free AU Shipping' },
  { datakey: 'nz_available', value: true, title: 'NZ Shipping Available' },
  { datakey: 'direct_import', value: true, title: 'Direct import' },
  { datakey: 'on_promotion', value: true, title: 'Price Drop' },
  { datakey: 'in_stock', value: true, title: 'In Stock' },
  { datakey: 'in_stock', value: false, title: 'Out of Stock' },
  { datakey: 'on_my_sku_list', value: false, title: 'Not on My SKU List' },
  { datakey: 'on_my_sku_list', value: true, title: 'Added to My SKU List' },
  { datakey: 'discontinued', value: true, title: 'Discontinued' },
  { datakey: 'recently', value: 7, title: 'Last 7 days' },
  { datakey: 'recently', value: 14, title: 'Last 14 days' },
];

export function checkFilterTitle(filter: FilterData, categoryList?: any[]) {
  const ft = { ...filter };
  if (ft.datakey == 'q') {
    ft.title = `Search "${ft.value}"`;
  } else if (ft.datakey == 'cat') {
    ft.title = `Category: ${categoryList?.length ? categoryList.find(c => c.category_id == Number(ft.value))?.title : ft.value}`;
  } else if (ft.datakey == 'price') {
    const priceArr = ft.value.split('-');
    if (priceArr[0] === '' && priceArr[1] !== '') {
      ft.title = 'Price < ' + formatCurrency(priceArr[1], 0);
    } else if (priceArr[0] !== '' && priceArr[1] === '') {
      ft.title = 'Price >' + formatCurrency(priceArr[0], 0);
    } else {
      ft.title =
        'Price: ' +
        formatCurrency(priceArr[0], 0) +
        ' - ' +
        formatCurrency(priceArr[1], 0);
    }
  } else if (filterKeyTitleMap.find((f: any) => f.datakey == ft.datakey)) {
    const fmap = filterKeyTitleMap.find(
      (f: any) =>
        f.datakey == ft.datakey && f.value.toString() == ft.value.toString()
    );
    if (fmap) ft.title = fmap.title;
    else return null;
  } else {
    return null;
  }
  return ft;
}

const tempCache = new Map();
tempCache.set('limit', 40);

export function parseUrlToFetchParams(
  basePath: string,
  paths: any[] = [],
  searchParams: Obj = {},
  categories: any[]
) {
  const defaultLimit = tempCache.get('limit');
  const defaultSortBy =
    basePath == 'catalogsearch'
      ? 'relevance'
      : basePath == 'new-arrivals'
        ? 'approve_time'
        : 'sales_volume';
  const defaultSortOrder = basePath == 'catalogsearch' ? '' : 'desc';
  const category = getCategoryByPaths(paths, categories);
  const categoryParam = category ? { category_id: category?.category_id } : {};
  const params = parseSearchParams(searchParams);
  // console.log('##############==>', params);
  let queryParams: Obj =
    basePath == 'categories'
      ? {
          limit: defaultLimit,
          sort_by: defaultSortBy,
          sort_order: defaultSortOrder,
          ...categoryParam,
          ...params,
        }
      : basePath == 'promotion'
        ? {
            on_promotion: true,
            limit: defaultLimit,
            sort_by: defaultSortBy,
            sort_order: defaultSortOrder,
            ...categoryParam,
            ...params,
          }
        : basePath == 'new-arrivals'
          ? {
              new_arrival: true,
              limit: defaultLimit,
              sort_by: defaultSortBy,
              sort_order: defaultSortOrder,
              ...categoryParam,
              ...params,
            }
          : { limit: defaultLimit, ...categoryParam, ...params };

  queryParams.limit != defaultLimit &&
    tempCache.set('limit', queryParams.limit);
  if (sessionStorage.isLogin !== 'true') {
    const publicKeys = ['limit', 'page_no', 'sort_by', 'sort_order'];
    const limitKeys =
      basePath == 'catalogsearch'
        ? [...publicKeys, 'keywords']
        : basePath == 'categories'
          ? [...publicKeys, 'category_id']
          : basePath == 'promotion'
            ? [...publicKeys, 'on_promotion', 'category_id']
            : basePath == 'new-arrivals'
              ? [...publicKeys, 'new_arrival', 'category_id']
              : [...publicKeys];
    queryParams = pickData(queryParams, [...limitKeys], null);
    queryParams = pickBy(queryParams, value => value != null);
  }
  return queryParams;
}

export function staticGo(
  path: string,
  queryObj: Obj = {},
  gotoTop: boolean = false
) {
  let url = path;
  if (queryObj && Object.keys(queryObj).length) {
    Object.entries(queryObj).forEach(([key, val], i) => {
      url += `${i == 0 ? '?' : '&'}${key}=${encodeURIComponent(val)}`;
    });
  }
  //url += `?${new URLSearchParams({ ...queryObj })}`;
  window.history.pushState(null, '', url);
  gotoTop && window.scrollTo({ left: 0, top: 0, behavior: 'instant' } as any);
}
